﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WaveringLand_Launcher.Model;
using System.Text.Json;

namespace WaveringLand_Launcher.Helper
{
    public static class ConfigurationHelper
    {
        public static WllConfig GetConfig()
        {
            
            //check file
            if (File.Exists(PathHelper.ConfigPath) is false)
            {
                File.WriteAllText(PathHelper.ConfigPath, JsonSerializer.Serialize(new WllConfig()));
            }

            //read config
            var configstr = File.ReadAllText(PathHelper.ConfigPath);
            if (string.IsNullOrEmpty(configstr))
            {
                return new WllConfig();
            }
            try
            {

                return JsonSerializer.Deserialize<WllConfig>(configstr);
            }
            catch (Exception)
            {

                return new WllConfig();
            }
        }

        public static void SaveConfig(WllConfig config)
        {
            File.WriteAllText(PathHelper.ConfigPath, JsonSerializer.Serialize(config));
        }

        public static void UpdateRefreshToken(string oldtoken,string newtoken)
        {
            var config = GetConfig();
            config.Accounts.Where(x => x.Password == oldtoken).First().Password = newtoken;
            SaveConfig(config);
        }

    }
}
